﻿using AdminWeb.Areas.Sys.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using SqlSugar;
using System.Threading.Tasks;
using XW.Core;
using XW.Data;
using XW.Utils;
using XW.Web.Framework;
using XW.Web.Framework.Jwt;

namespace AdminWeb.Areas.Sys.Controllers
{
	[Area("Sys")]
	[Authorize]
	public class RoleController : BaseController
	{
		private readonly IOptions<JwtSecurityTokenOptions> _jwtOptions;
		private readonly ILogger<RoleController> _logger;
        private readonly SqlSugarRepository<SysRole> _roleRep;
        private readonly SqlSugarRepository<SysRoleMenu> _roleMenuRep;
        private readonly SqlSugarRepository<SysMenu> _menuRep;

        public RoleController(ILogger<RoleController> logger, IOptions<JwtSecurityTokenOptions> jwtOptions, SqlSugarRepository<SysRole> roleRep
			,SqlSugarRepository<SysRoleMenu> roleMenuRep, SqlSugarRepository<SysMenu> menuRep)
		{
			_logger = logger;
			_jwtOptions = jwtOptions;
			_roleRep = roleRep;
            _roleMenuRep = roleMenuRep;
			_menuRep = menuRep;
        }
		/// <summary>
		/// 角色列表
		/// </summary>
		/// <returns></returns>
		public IActionResult List()
		{
			// string url = Request.GetEncodedPathAndQuery();
			return View();
		}
		/// <summary>
		/// 分页查询
		/// </summary>
		/// <returns></returns>
		public async Task<IActionResult> PageAsync()
		{
			var pageModel = CommonHelper.GetPageModel4Form<UserPageModel>();
			RefAsync<int> count = 0;
			var query = _roleRep.AsQueryable();
			pageModel.Keyword = pageModel.Keyword.SafeTrim();
			// 关键字查询
			query.WhereIF(pageModel.Keyword.IsNotNullAndEmpty(),
				u => u.Name.Contains(pageModel.Keyword));

			// 排序
			if (pageModel.SortField.IsNotNullAndEmpty())
			{
				query.OrderByPropertyName(pageModel.SortField, pageModel.SortType == "desc" ? OrderByType.Desc : OrderByType.Asc);
			}
			// 排序
			var list = await query.ToPageListAsync(pageModel.Page, pageModel.Limit, count);

			return GetSuccessResult(new { items = list, count = count.Value });
		}


		/// <summary>
		/// 编辑
		/// </summary>
		/// <returns></returns>
		public IActionResult Edit(long id = 0)
		{
			SysRole role = null;
			if (id > 0)
			{
				role = _roleRep.GetById(id);
				if (role == null)
				{
					return Content("<h1>角色不存在！</h1>");
				}
			}
			else
			{
				role = new SysRole();
			}

			//ViewData["CurrentUser"] = user;
			return View(role);
		}
		
		/// <summary>
		/// 保存
		/// </summary>
		/// <returns></returns>
		[Authorize]
		public IActionResult Save()
		{
			string? Name = this.Request.Form["Name"];
		 
			long id = CommonHelper.ToInt64(this.Request.Form["id"]);
			if (Name.IsNullOrEmpty())
			{
				return GetErrorResult("角色名不能为空");
			}
			if (id == 0)
			{ 
				var role = new SysRole();
				role.Name = Name;
				_roleRep.Insert(role);
			}
			else
			{
				_roleRep.AsUpdateable()
			   .SetColumns(u => u.Name == Name) 
			   .setColumnsUpdateUserAndTime()
			   .Where(u => u.Id == id).ExecuteCommand();
			}

			return GetSuccessResult("保存成功！");

		}

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public async Task<IActionResult> Delete(long id = 0)
		{
			SysRole role = _roleRep.GetById(id);
			if (role == null)
			{
				return GetErrorResult("角色不存在");
			}
			var result = await _roleRep.DeleteByIdAsync(id);

			return GetSuccessResult("操作成功！");
		}
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public async Task<IActionResult> BatDelete()
		{
			string ids = Request.Form["ids"];
			if (ids.IsNullOrEmpty()) { 
				return GetErrorResult("请选择需要删除的数据");
			}
			var idlist = ids.Split(',').Select(d=> CommonHelper.ToInt64(d)).ToArray();
			   var result = await _roleRep.DeleteAsync(d=> idlist.Contains(d.Id));
			return GetSuccessResult("操作成功！");
		}

        /// <summary>
        /// 获取角色菜单
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public async Task<IActionResult> GetRoleMenus()
        {
            long roleId = CommonHelper.ToInt64( Request.Form["id"]);
            if (roleId == 0)
            {
                return GetErrorResult("请选择【一个】角色！");
            } 
            var menuIds = await _roleMenuRep.AsQueryable().Where(d=>d.RoleId == roleId).Select(d=>d.MenuId).ToListAsync();
			var menus = await _menuRep.AsQueryable().Where(d => d.IsDelete == false).ToListAsync();
			var ids = menuIds.Select(d => CommonHelper.ToString(d)).ToList(); 
            return GetSuccessResult(new { menus = menus, menuIds = ids });
        }
        /// <summary>
        /// 保存角色菜单
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public async Task<IActionResult> SaveRoleMenus() {

            long roleId = CommonHelper.ToInt64(Request.Form["roleId"]);
            var menusIds = CommonHelper.ToString(Request.Form["menusIds"]);
            if (roleId == 0)
            {
                return GetErrorResult("请选择【一个】角色！");
            }
            var menus = menusIds.Split(',').Select(d => new SysRoleMenu
            {
                RoleId = roleId,
                MenuId = CommonHelper.ToInt64(d)
            }).ToList();

            await _roleMenuRep.DeleteAsync(d=>d.RoleId == roleId);
			
            await _roleMenuRep.InsertRangeAsync(menus);
            
            
            return GetSuccessResult();
        }
    }
}
